<template>
  <van-nav-bar title="重新发布" left-arrow @click-left="goBack" />
  <div :class="['background-container', isWechat ? 'wechat-backgroud-padding' : 'browser-backgroud-padding']">
    <div :class="['form-container', isWechat ? 'wechat-form-padding' : 'browser-form-padding']">
      <van-notice-bar v-if="configStore.checkForbid" left-icon="volume-o" text="当前处于夜间休息时段，寻物启事功能已关闭，请您谅解!" />
      <van-form ref="formRef" :disabled="configStore.checkForbid">
        <van-field name="radio" label="类型" label-width="5rem" size="large" center>
          <template #input>
            <van-radio-group v-model="form.postType" :disabled="configStore.checkForbid" checked-color="#667eea"
              direction="horizontal">
              <van-radio name="0">寻人</van-radio>
              <van-radio name="1">寻物</van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <van-field v-model="form.lostName" size="large" label="名称/姓名" label-width="5rem" maxlength="16"
          :rules="[{ required: true, message: '请输入名称或姓名' }]" placeholder="请输入物品名称或人员姓名" />

        <van-field v-model="form.lostTime" size="large" label="丢失时间" label-width="5rem"
          :rules="[{ required: true, message: '请选择丢失时间' }]" readonly placeholder="请选择丢失时间"
          @click="showDatetimePicker" />
        <van-popup v-model:show="showPicker" round position="bottom">
          <van-picker-group title="丢失时间" :tabs="['选择日期', '选择时间']" next-step-text="下一步" @confirm="confirmDatetime"
            @cancel="showPicker = false">
            <van-date-picker v-model="pickerDate" />
            <van-time-picker v-model="pickerTime" />
          </van-picker-group>
        </van-popup>

        <van-field v-model="form.lostPlace" size="large" label="丢失地点" label-width="5rem" maxlength="50"
          :rules="[{ required: true, message: '请输入丢失地点' }]" placeholder="请输入丢失地点" />

        <van-field v-model="form.description" size="large" label="描述信息" label-width="5rem"
          :rules="[{ required: true, message: '请输入描述信息' }]" type="textarea" rows="4" maxlength="500" show-word-limit
          placeholder="请输入物品特征或人员外貌特征等信息" />

        <van-field v-model="form.contactPlace" size="large" label="联系地点" label-width="5rem" maxlength="50"
          :rules="[{ required: true, message: '请输入联系地点' }]" placeholder="请输入联系地点" />

        <van-field v-model="form.contactPhone" size="large" label="联系人电话" label-width="5rem" type="number"
          maxlength="11"
          :rules="[{ required: true, message: '请输入联系人电话' }, { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' }]"
          placeholder="请输入联系人电话" />

        <van-button size="large" color="#667eea" block :disabled="configStore.checkForbid" @click="handleSubmit"
          class="submit-button">
          发布
        </van-button>
      </van-form>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getImpactType, getImpactCode } from '@/utils/auth'
import { useConfigStore } from '@/stores/config';
import { findPostGet, findPostEdit } from '@/api/findPost';

const route = useRoute();
const router = useRouter();

const configStore = useConfigStore();

const isWechat = ref(false);
const formRef = ref(null);
const form = ref({
  postId: null,
  postType: '0',
  lostName: '',
  lostTime: '',
  lostPlace: '',
  description: '',
  contactPlace: '',
  contactPhone: '',
  impactType: getImpactType(),
  impactCode: getImpactCode(),
});

const showPicker = ref(false);
const pickerDate = ref([]);
const pickerTime = ref([])

onMounted(() => {
  const userAgent = navigator.userAgent.toLowerCase();
  isWechat.value = userAgent.includes('micromessenger');
  const now = new Date();
  pickerDate.value = [now.getFullYear().toString(), (now.getMonth() + 1).toString(), now.getDate().toString()];
  pickerTime.value = [now.getHours().toString(), now.getMinutes().toString()];
  document.body.style.overflow = 'hidden';
  findPostGet(route.query.postId).then(res => {
    form.value = res.data;
  }).finally(() => {
    closeToast();
  });
});

onUnmounted(() => {
  document.body.style.overflow = '';
});

const goBack = () => {
  router.back();
};

const showDatetimePicker = () => {
  if (configStore.checkForbid) return;
  showPicker.value = true;
};

const confirmDatetime = (value) => {
  form.value.lostTime = pickerDate.value.join('-') + ' ' + pickerTime.value.join(':');
  showPicker.value = false;
};

const handleSubmit = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
  } catch (errors) {
    console.error('表单校验失败:', errors);
    return;
  }
  findPostEdit(form.value).then(res => {
    showDialog({
      message: '发布成功',
      confirmButtonColor: '#667eea',
    }).then(() => {
      clearForm();
      router.push({ path: '/findPost/history' });
    }).catch(() => {});
  })
};

const clearForm = () => {
  form.value = {
    postId: null,
    postType: '0',
    lostName: '',
    lostTime: '',
    lostPlace: '',
    description: '',
    contactPlace: '',
    contactPhone: '',
    impactType: getImpactType(),
    impactCode: getImpactCode(),
  };
};
</script>

<style scoped>
.background-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  overflow: hidden;
}

.browser-backgroud-padding {
  padding: 20px;
}

.wechat-backgroud-padding {
  padding: 30px 20px;
}

.form-container {
  background-color: rgba(255, 255, 255, 1);
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  max-width: 450px;
  margin: 0 auto;
}

.browser-form-padding {
  padding: 5px;
}

.wechat-form-padding {
  padding: 10px;
}

.submit-button {
  margin: 30px auto;
  border-radius: 8px;
  border: none;
  font-size: 18px;
  max-width: 90%;
}

.history-link {
  text-align: right;
  color: #fff;
}

.history-link a {
  text-decoration: none;
  transition: color 0.3s ease;
  color: #fff;
}

.history-link a:hover {
  text-decoration: underline;
}

.browser-history-link {
  margin-top: 15px;
  padding-right: 5px;
}

.wechat-history-link {
  margin-top: 25px;
  padding-right: 10px;
}
</style>
